package com.ecplatform.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ecplatform.common.constant.MessageConstants;
import com.ecplatform.common.exception.UserException;
import com.ecplatform.common.utils.JwtUtil;
import com.ecplatform.common.utils.PasswordEncryptionUtil;
import com.ecplatform.user.mapper.UserMapper;
import com.ecplatform.user.pojo.dto.UserDTO;
import com.ecplatform.user.pojo.po.User;
import com.ecplatform.user.pojo.vo.UserVO;
import com.ecplatform.user.service.IUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import static com.ecplatform.common.constant.MessageConstants.*;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final PasswordEncryptionUtil passwordEncryptionUtil;

    private final JwtUtil jwtUtil;

    private final UserMapper userMapper;

    @Override
    public User getByUsername(String username) {
        // 利用mybatis-plus的查询方法，查询username为username的用户 TODO: 这里应该用mybaties-plus
//        return userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        return userMapper.getByUsername(username);
    }

    /**
     * 用户登录
     * @param userDTO
     * @return
     */
    @Override
    public UserVO userLogin(UserDTO userDTO) throws UserException {
        // 1. 转换UserDTO到User
        User tUser = new User();
        BeanUtils.copyProperties(userDTO, tUser);

        // 2. 调用mybatis-plus的查询方法，查询username为username的用户
        User user = this.getByUsername(tUser.getUsername());

        // 3. 判断用户是否存在
        if(user == null){
            throw new UserException(UserIsNotExist);
        }

        // 4. 判断密码是否正确
//        String newPassword = passwordEncryptionUtil.encryptPassword(tUser.getPassword());
        if(!passwordEncryptionUtil.verifyPassword(tUser.getPassword(), user.getPassword())) {
            throw new UserException(PasswordError);
        }

        // 5. 判断用户是否被禁用
        if (user.getStatus() == 0) {
            throw new UserException(UserIsForbidden);
        }

        // 6. 构建jwt token
        String token = jwtUtil.generateToken(user.getId());

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setToken(token);

        return userVO;
    }

    @Override
    public void insertUser(User user) {

        // 加密密码
        user.setPassword(passwordEncryptionUtil.encryptPassword(user.getPassword()));

        // 设置角色
        user.setRole(MessageConstants.Custom);

        userMapper.saveUser(user);
    }
}
